package org.mainlove.project.web;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.mainlove.project.web.framework.util.HttpMethod;
import org.mainlove.project.web.framework.util.TemplateConfiguration;

@SuppressWarnings("serial")
public abstract class LabsServlet extends HttpServlet {

	private static final String REQUEST_SUFFIX = ".love";

	@Override
	public void init() throws ServletException {
		super.init();

		String templateRoot = getServletContext().getRealPath("/");
		TemplateConfiguration.setTemplateRoot(templateRoot + File.separator + "template");

	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			dispathRequest(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected abstract void dispathRequest(HttpServletRequest request, HttpServletResponse response)
			throws Exception;

	protected String getRequestServiceName(HttpServletRequest request) {

		String requeestURI = request.getRequestURI();

		String path = request.getContextPath();

		return requeestURI.substring(path.length()+1, requeestURI.lastIndexOf(REQUEST_SUFFIX));

	}

	protected Boolean checkMethod(String _MethodName, String _MethodWay, String methodName,
			String methodWay) throws Exception {

		if (!_MethodName.equals(methodName)) {
			return false;
		}

		if (_MethodWay.equals(HttpMethod.ALL)) {
			return true;

		}

		if (_MethodWay.equals(methodWay)) {

			return true;

		} else {
			// throw UnsupportedHttpMethodException();
			throw new Exception("不支持");
		}

	}

	protected JSONObject getRequestJsonObject(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException, IOException, JSONException {
		response.setContentType("application/json");
		final Map<?, ?> parameterMap = request.getParameterMap();

		JSONObject jo = new JSONObject();
		for (Map.Entry<?, ?> entry : parameterMap.entrySet()) {

			jo.put(entry.getKey().toString(), entry.getValue().toString());
		}

		return jo;
	}

}
